import json
import subprocess
import os

def strip_obj_c(string):
	return string.rstrip("\"\n").lstrip("@\"")

def add_obj_c(string):
	return '@\"'+string+'\"'

def convert_to_json(file): 
	enDict = {}
	desciptionDict = {}
	keys = []
	for line in file:
		if '#define EN_' in line:
			lineSplitArray = line.split(' ',2)
			#print lineSplitArray
			enDict[lineSplitArray[1]] = [strip_obj_c(lineSplitArray[2])]
		if 'NSLocalizedString' in line:
			commaSplit = line.split(',',1)
			description = strip_obj_c(commaSplit[1].rstrip(')\n').lstrip(' '))
			parSplit = commaSplit[0].split('(',1)
	 		key = parSplit[1].strip()
	 		desciptionDict[key] = description
	 	if 'OTRLanguageManager' in line:
	 		keys.append(line.split(' ')[1])

	 		pass

	#print len(enDict)
	#print len(desciptionDict)

	combiniedDict = {}
	for key in enDict:
		newKey = key[3:]
		if newKey not in keys:
			#print key
			print "error: "+newKey
		else:
			combiniedDict[newKey] = {'string':enDict[key][0],'comment':desciptionDict[key]}
	#print combiniedDict
	newFile = open('strings.json', 'w')
	newFile.write(json.dumps(combiniedDict,sort_keys=True,indent=4))
	newFile.close()

def json_to_strings(strings_dict, strings_h_path, temp_strings_h_path):
	stringsFile = open(strings_h_path, 'w')
	tempStrings = open(temp_strings_h_path, 'w')
	stringsFile.write('#import \"OTRLanguageManager.h\"\n\n')

	stringsFile.write('// DO NOT EDIT THIS FILE. EDIT strings.json then run python StringsConverter.py\n\n')

	for key in strings_dict:
		line = '#define '+key+' [OTRLanguageManager translatedString: '+add_obj_c(strings_dict[key]['string'])+']'
		stringsFile.write(line+'\n')
		line = 'NSLocalizedString('+add_obj_c(strings_dict[key]['string'])+','+add_obj_c(strings_dict[key]['comment'])+')'
		tempStrings.write(line+'\n')

	#Special case for .h file where always display the 'Default' in iOS system language
	default = 'NSLocalizedString(@\"Default\", @\"default string to revert to normal language behaviour\")'
	stringsFile.write('#define DEFAULT_LANGUAGE_STRING '+ default)
	tempStrings.write(default)

	stringsFile.close()
	tempStrings.close()

def genStrings(inputFilePath, outputDirectoryPath):
	subprocess.call(['genstrings', '-o', outputDirectoryPath, inputFilePath])

def main():
	script_directory = os.path.dirname(os.path.abspath(__file__))
	strings_json_path = os.path.join(script_directory, 'strings.json')
	strings_h_path = os.path.join(script_directory, 'Strings.h')
	temp_strings_h_path = os.path.join(script_directory, 'tempStrings.h')
	output_directory_path = os.path.join(os.path.join(script_directory, os.pardir), 'Base.lproj')

	# Compare Modification Dates
	strings_json_modified = os.path.getmtime(strings_json_path)
	strings_h_modified = os.path.getmtime(strings_h_path)

	# Bail out if strings.json hasn't been modified recently
	if strings_json_modified < strings_h_modified:
		print 'No changes to strings.json detected.'
		return

	strings_json_file = open(strings_json_path,'r')
	strings_dict = json.load(strings_json_file)
	json_to_strings(strings_dict, strings_h_path, temp_strings_h_path)
	strings_json_file.close()

	genStrings(inputFilePath=temp_strings_h_path, outputDirectoryPath=output_directory_path)
	os.remove(temp_strings_h_path)

if __name__ == "__main__":
	main()
